const STS = require('qcloud-cos-sts');

class TencentOSS {
    constructor(app) {
        this.app = app;
    }

    /**
     * 获取临时密钥
     */
    getCredential() {
        return new Promise((resolve, reject) => {
            let scope = [{
                secretId: this.app.config.tencent.SecretId,
                secretKey: this.app.config.tencent.SecretKey,
                bucket: this.app.config.tencent.bucket,
                region: this.app.config.tencent.region,
                prefix: '*',
                action: [
                    // 简单上传
                    'name/cos:PutObject',
                    'name/cos:PostObject',
                    // 分片上传
                    'name/cos:InitiateMultipartUpload',
                    'name/cos:ListMultipartUploads',
                    'name/cos:ListParts',
                    'name/cos:UploadPart',
                    'name/cos:CompleteMultipartUpload',
                    // 读取权限
                    // 'name/cos:GetService'
                ]
            }];
    
            let policy = STS.getPolicy(scope);

            STS.getCredential({
                secretId: this.app.config.tencent.SecretId,
                secretKey: this.app.config.tencent.SecretKey,
                policy: policy,
                proxy: '',
                durationSeconds: 3600, //密钥有效期
            }, function (err, credential) {
                if(err) {
                    reject(err);
                }
                resolve(credential);
            });
        })
    }
}

module.exports = TencentOSS;